package org.springblade.modules.develop.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springblade.core.tool.utils.SpringUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: 生成mybatis的session对象
 **/
public class MybatisUtils {
	private static SqlSessionFactory sqlSessionFactory = null;
	private static SqlSession session = null;


	private static void init() {
		try {
//            创建工厂
			sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
//            创建session对象
			session = sqlSessionFactory.openSession(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SqlSession getSession() {
		if (session == null) {
			init();
		}
		return session;
	}

	public static void close() {
		if (session != null) {
			session.close();
			session = null;
		}
	}

	public static <T> T getMapper(Class<T> tClass) {
		if (session == null) {
			init();
		}
		return session.getMapper(tClass);
	}

	public static void commit() {
		if (session != null) {
			session.commit();
		}
	}
}
